package com.atguigu.gmall.product.cron;

import com.atguigu.gmall.product.service.SkuInfoService;

import com.atguigu.gmall.serviceutil.redisson.SkuBloomTask;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/1 0:40
 */
@Slf4j
@Component
public class SkuIdBloomTask implements SkuBloomTask {
    @Autowired
    private SkuInfoService skuInfoService;
    @Qualifier("skuIdBloom")
    @Autowired
    private RBloomFilter<Object> skuIdBloom;
    public void rebuildBloomFilter() {
        log.info("开始重新构建 skuIdBloomFilter");
        if (skuIdBloom == null) {
            log.error("skuIdBloom 为 null，无法重新构建布隆过滤器");
            return;
        }
        skuIdBloom.delete();
        log.info("skuIdBloom 删除成功");
        if (!skuIdBloom.tryInit(1000000, 0.0003)) {
            log.error("skuIdBloom 初始化失败");
            return;
        }
        log.info("skuIdBloom 初始化成功");
        initData(skuIdBloom);
    }

    @Override
    public void initData(RBloomFilter<Object> skuIdBloom){
        log.info("开始初始化skuIdBloomFilter添加数据");
        //查出所有skuId,存放到bloomFilter中
        List<Long> skuIds =skuInfoService.getSkuIds();

        for (Long skuId : skuIds) {
            // 添加skuId
            skuIdBloom.add(skuId);
        }
        log.info("skuIdBloomFilter初始化完成,当前元素数量:{}",skuIdBloom.count());
    }


}
